package com.yazi.mxz.common.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyNoPermissionException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yazi.mxz.common.db.dao.MemberSpendDao;
import com.yazi.mxz.common.db.dao.OrderDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.MemberSpend;
import com.yazi.mxz.common.entity.beans.Order;
import com.yazi.mxz.common.entity.enums.OrderStatus;
import com.yazi.mxz.common.service.MemberSpendService;

@Service("memberSpendService")
public class MemberSpendServiceImpl extends BasicService<MemberSpend> implements MemberSpendService {
	private static Logger log = LoggerFactory.getLogger(MemberSpendServiceImpl.class);

	@Resource
	MemberSpendDao memberSpendDao;
	@Resource
	OrderDao orderDao;
	
	@Override
	protected Dao<MemberSpend> getDao() {
		return memberSpendDao;
	}
	
	@Override
	public MemberSpend addByMember(Member member, String serialCode) throws MyException {
		log.debug("addByMember：memberId={},serialCode={}", member.getMemberId(), serialCode);
		
		// 检查消费记录是否已经存在
		MemberSpend memberSpend = memberSpendDao.get(serialCode);
		if (null != memberSpend) {
			if (memberSpend.getMember().equals(member)) {
				throw new MyNoPermissionException("不能重复添加");
			} else {
				throw new MyNoPermissionException("已被其它用户添加");
			}
		}
		
		memberSpend = new MemberSpend();
		ValueFactory.validate(memberSpend);
		memberSpend.setMember(member);
		memberSpend.setSerialCode(serialCode);
		memberSpend.setSpendTime(DateUtil.getTimeStamp());
		
		// 检查订单(已完成)记录是否存在
		Order order = new Order();
		order.setSerialCode(serialCode);
		order.setStatus(OrderStatus.SUCCESS.ordinal());
		List<Order> orderList = orderDao.listByExample(order, new Searching()).getList();
		if (orderList.size() == 1) {
			order = orderList.get(0);
			memberSpend.setSpend(order.getRealCost());
			memberSpend.setIsChecked(true);
		}
		
		return memberSpendDao.persist(memberSpend);
	}

}
